package com.example.criminalintent.model;

import java.util.Date;
import java.util.UUID;

import org.json.JSONException;
import org.json.JSONObject;

public class Crime {
	
	// properties of Crime object
	private UUID mID;
	private String mTitle;
	private Date mDate;
	private boolean mSolved;
	// hold the Photo object captured by user
	private Photo mPhoto;
	
	// keys of JSON Object
	private static final String JSON_ID = "id";
	private static final String JSON_TITLE = "title";
	private static final String JSON_SOLVED = "solved";
	private static final String JSON_DATE = "date";
	private static final String JSON_PHOTO = "photo";
	
	public Crime() {
		//Generate unique identifier
		mID = UUID.randomUUID();
		mDate = new Date();
	}
	
	/**
	 * Convert JSONObject to Crime to load Crime List
	 * @param jsonObject
	 * @throws JSONException
	 */
	public Crime(JSONObject jsonObject) throws JSONException {
		mID = UUID.fromString(jsonObject.getString(JSON_ID));
		if (jsonObject.has(JSON_TITLE)) {
			mTitle = jsonObject.getString(JSON_TITLE);
		}
		if (jsonObject.has(JSON_SOLVED)) {
			mSolved = jsonObject.getBoolean(JSON_SOLVED);
		}
		if (jsonObject.has(JSON_DATE)) {
			mDate = new Date(jsonObject.getLong(JSON_DATE));
		}
		if (jsonObject.has(JSON_PHOTO)) {
			mPhoto = new Photo(jsonObject.getJSONObject(JSON_PHOTO));
		}
	}

	public String getTitle() {
		return mTitle;
	}

	public void setTitle(String title) {
		mTitle = title;
	}

	public UUID getID() {
		return mID;
	}

	public Date getDate() {
		return mDate;
	}

	public void setDate(Date date) {
		mDate = date;
	}

	public boolean isSolved() {
		return mSolved;
	}

	public void setSolved(boolean solved) {
		mSolved = solved;
	}

	public Photo getPhoto() {
		return mPhoto;
	}

	public void setPhoto(Photo photo) {
		mPhoto = photo;
	}

	@Override
	public String toString() {
		return mTitle;
	}
	
	/**
	 *  convert Crime object to JSON object
	 * @return JSONObject
	 * @throws JSONException
	 */
	public JSONObject toJSON() throws JSONException {
		JSONObject object = new JSONObject();
		object.put(JSON_ID, mID.toString());
		object.put(JSON_TITLE, mTitle);
		object.put(JSON_SOLVED, mSolved);
		object.put(JSON_DATE, mDate.getTime());
		if (mPhoto != null) {
			object.put(JSON_PHOTO, mPhoto.toJson());
		}
		return object;
	}
}
